package me.zhengjie.modules.management.job;

import cn.hutool.core.util.ObjectUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.management.domain.RoomUser;
import me.zhengjie.modules.management.domain.RoomUserView;
import me.zhengjie.modules.management.mapper.MrIntervalTimeMapper;
import me.zhengjie.modules.management.mapper.MrUserViewMapper;
import me.zhengjie.modules.management.mapper.UserMapper;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: chenxin.jiang
 * @Date: 2020/12/22
 * @Description:
 */
@Component
@RequiredArgsConstructor
public class MrUserJob extends IJobHandler {

    private final MrUserViewMapper mrUserViewMapper;
    private final UserMapper userMapper;
    private final MrIntervalTimeMapper mrIntervalTimeMapper;

    @XxlJob("mr-user")
    @Override
    public ReturnT<String> execute(String s) throws Exception {

        //  通过类型是user获取间隔时间
        Long intervalTime = mrIntervalTimeMapper.findIntervalTimeByType("user");
        //  如果数据库中未查询到时间，给间隔时间赋值2个小时
        if (intervalTime == null) {
            intervalTime = 7200000L;
        }   //  else 的情况为数据库中获取的时间有值，直接取数据库中的值
        //  当前系统时间
        Date nowTime = new Date();
        Date startTime = new Date(nowTime.getTime() - intervalTime);
        //查询中间库视图里时间内修改数据。
        List<RoomUserView> roomUserViews=mrUserViewMapper.findRoomUserView(startTime);

        if (ObjectUtil.isNotEmpty(roomUserViews)) {
            //遍历查出来的用户数据
            List<RoomUser> users = new ArrayList<>();
            for (RoomUserView roomUserView : roomUserViews) {
                //根据userId从sys_user里查询用户数据
                RoomUser rUser = userMapper.findUserById(roomUserView.getUserId());
                if (ObjectUtil.isEmpty(rUser)) {
                    //如果在sys_user里查不到数据，说明这条数据是新增的，默认设置密码，启用状态等信息
                    rUser = new RoomUser();
                    rUser.setId(roomUserView.getUserId());
                    rUser.setDept(roomUserView.getIdDepartment());
                    rUser.setUserName(roomUserView.getJobNumber());
                    rUser.setNickName(roomUserView.getName());
                    rUser.setGender(ObjectUtil.isNotEmpty(roomUserView.getGender()) && true == roomUserView.getGender() ? "2" : "1");
                    rUser.setPhone(roomUserView.getMobilePhone());
                    rUser.setEmail(roomUserView.getEmail());
                    rUser.setAvatarPath(roomUserView.getPictureUrl());
                    rUser.setEnName(roomUserView.getEngName());
                    rUser.setOrgId(roomUserView.getIdOrganization());
                    rUser.setPassword("$2a$10$f47TSKrW58RmJ1ksdJnbPetvPW6RZgggssfxN.MO.ozDq2oaQk0ZW");
                    rUser.setIsAdmin(false);
                    rUser.setEnabled(true);
                    rUser.setOrgCode(roomUserView.getCompanyCode());
                    rUser.setRole(20);
                    users.add(rUser);
                    //userMapper.insertUser(rUser);
                } else {
                    //如果在sys_user里查到数据，说明这条数据已存在执行更新
                    rUser.setId(roomUserView.getUserId());
                    rUser.setDept(roomUserView.getIdDepartment());
                    rUser.setUserName(roomUserView.getJobNumber());
                    rUser.setNickName(roomUserView.getName());
                    rUser.setGender(ObjectUtil.isNotEmpty(roomUserView.getGender()) && true == roomUserView.getGender() ? "2" : "1");
                    rUser.setPhone(roomUserView.getMobilePhone());
                    rUser.setEmail(roomUserView.getEmail());
                    rUser.setAvatarPath(roomUserView.getPictureUrl());
                    rUser.setEnName(roomUserView.getEngName());
                    rUser.setOrgId(roomUserView.getIdOrganization());
                    rUser.setOrgCode(roomUserView.getCompanyCode());
                    userMapper.updateUser(rUser);
                }
            }
            //如果有新增的数据，新增进sys_user表和users_roles表
            if (ObjectUtil.isNotEmpty(users)) {
                //System.err.println(users.size());
                userMapper.insertUser(users);
                userMapper.insertRoles(users);

            }

            //查出sys_user中的所有username（工号），比对视图里面没有的，进行删除
            List<String> jobNumList=userMapper.findAllJobNum();
            for (String jobNum : jobNumList) {
                RoomUserView ruv=mrUserViewMapper.findRoomUserViewByJobNum(jobNum);
                if(ruv==null){
                    userMapper.deleteByJobNum(jobNum);
                }
            }


        }

        return ReturnT.SUCCESS;
    }
}
